package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.entity.CartInfo;
import com.atguigu.gmall.cart.service.CartBizService;
import com.atguigu.gmall.cart.service.impl.CartBizServiceImpl;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class CartApiController {

    @Autowired
    CartBizService cartBizService;

    /**
     * 获取购物车商品列表
     */
    @GetMapping("/cartList")
    public Result getCartList(){
        List<CartInfo> cartInfos =  cartBizService.displayItems();
//        List<CartInfo> cartInfos =  cartBizService.getCartList();
        return Result.ok(cartInfos);
    }

    /**
     * 修改数量
     * @param skuId
     * @param num
     * @return
     */
    @PostMapping("/addToCart/{skuId}/{num}")
    public Result updateItemNum( @PathVariable Long skuId,@PathVariable Integer num){
        String cartKey = CartBizServiceImpl.determinCartKey();
        cartBizService.updateItemNum(skuId,num,cartKey);
        return Result.ok();
    }

    /**
     * 是否选中商品
     * @param checked
     * @param skuId
     * @return
     */
    @GetMapping("/checkCart/{skuId}/{checked}")
    public Result checkItem(@PathVariable Integer checked, @PathVariable Long skuId) throws Exception {
        if (checked == 1 || checked == 0){
            String cartKey = CartBizServiceImpl.determinCartKey();
            cartBizService.checkItem(cartKey,skuId,checked);
        }else {
            throw new GmallException(ResultCodeEnum.INVAILD_PARAM);
        }
        return Result.ok();
    }

    /**
     * 删除某个sku
     * @param skuId
     * @return
     */
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCart(@PathVariable String skuId){
        String cartKey = CartBizServiceImpl.determinCartKey();
        cartBizService.deleteItem(cartKey,skuId);
        return Result.ok();
    }


}
